//引入校验文件
import WxValidate from './../../tools/WxValidate'

var fileID = '';

var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var day1 = day + 1;
var day2 = day1 + 1;
var currentDate = year + '-' + month + '-' + day;
var tomorrow = year + '-' + month + '-' + day1;
var dayOfTomorrow = year + '-' + month + '-' + day2;

Page({

  /**
   * 页面的初始数据
   */
  data: {

    array: ['信息工程学院', '公路学院', '建工学院', '经管学院', '公用'],
    index: 0,
    allValue: '',
    tempFilePaths: '',
    roomFilePaths: './../../images/upfile.png',

    mapName: '',
    mapAddress: '',
    mapLatitude: '',
    mapLongitude: '',

    currentDate: currentDate,
    tomorrow: tomorrow,
    dayOfTomorrow: dayOfTomorrow,
    dayFlag: '0',
    dayOne: {
      specDate: null,
      openTime: null
    },
    dayTwo: {
      specDate: null,
      openTime: null
    },
    dayThree: {
      specDate: null,
      openTime: null
    },


    form: {
      name: '',
      address: '',
      containNum: '',
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initValidate();
  },


  /* 显示提示框 */
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },

  /* 初始化校验规则 */
  initValidate() {
    const rules = {
      name: {
        required: true,
        minlength: 3
      },
      address: {
        required: true,
        minlength: 3
      },
      containNum: {
        required: true,
        number: true
      },
    }
    const messages = {
      name: {
        required: '请填写会议室名称',
        minlength: '请输入正确的名称'
      },
      address: {
        required: '请填写会议室地址',
        minlength: '请输入正确的名称'
      },
      containNum: {
        required: '请填写可容纳的人数',
        number: "请填写数字"
      },
    }
    this.WxValidate = new WxValidate(rules, messages);
  },

  /* 地图选择地点 */
  getLocation: function () {
    let _this = this;
    wx.getSetting({
      success(res) {
        console.log(res.authSetting)
        let result = res.authSetting['scope.userLocation'];
        // 判断定位的授权
        if (res.authSetting['scope.userLocation']) {
          _this.chooseLocation();
        }else {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              _this.chooseLocation();
              return;
            }
          })
        }
      }
    })
  },
  chooseLocation:function(){
    let _this = this;
    wx.chooseLocation({
      success(res){
        var name = res.name
        var address = res.address
        var latitude = res.latitude
        var longitude = res.longitude
        _this.setData({
          mapName: name,
          mapAddress: address,
          mapLatitude: latitude,
          mapLongitude: longitude
        })
      }
    })
  },

  /* 选择图片 */
  choose: function () {
    var that = this
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        wx.showLoading({
          title: '上传中',
        });
        let filePath = res.tempFilePaths[0];
        const name = Math.random() * 1000000;
        const cloudPath = name + filePath.match(/\.[^.]+?$/)[0];
        wx.cloud.uploadFile({
          cloudPath, //云存储图片名字
          filePath, //临时路径
          success: res => {
            that.setData({
              roomFilePaths: res.fileID, //云存储图片路径,可以把这个路径存到集合，要用的时候再取出来
            });
            fileID = res.fileID;
          },
          fail: e => {
            console.error('[上传图片] 失败：', e)
          },
          complete: () => {
            wx.hideLoading()
          }
        });
      }
    })
  },

  /* 切换日期选项 */
  changeDayFlag: function (e) {
    this.setData({
      dayFlag: e.currentTarget.dataset.dayflag
    })
  },

  /* 缓存日期选项 */
  checkboxChange: function (e) {

    //对时间进行变化
    let time = e.detail.value,
      timeObj = {};
    for (let i = 0; i < time.length; i++) {
      let tempObj = {};
      tempObj['state'] = 1;
      tempObj['appointmentId'] = null;
      timeObj[time[i]] = tempObj;
    }

    if (this.data.dayFlag === '0') { //第一天选择项
      //对时间进行变化
      this.setData({
        dayOne: {
          specDate: currentDate,
          openTime: timeObj
        }
      })
    } else if (this.data.dayFlag === '1') {
      this.setData({
        dayTwo: {
          specDate: tomorrow,
          openTime: timeObj
        }
      })
    } else if (this.data.dayFlag === '2') {
      this.setData({
        dayThree: {
          specDate: dayOfTomorrow,
          openTime: timeObj
        }
      })
    }
  },

  //表单提交按钮
  formSubmit: function (e) {
    // 对数据进行验证
    let result = e.detail.value;

    //校验表单
    if (!this.WxValidate.checkForm(result)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false;
    }

    //校验通过，整理输入数据库的数据
    //时间
    let timeArr = [];
    timeArr.push(this.data.dayOne);
    timeArr.push(this.data.dayTwo);
    timeArr.push(this.data.dayThree);

    result["timeList"] = timeArr;
    result['mainImage'] = fileID;

    //地点
    let address = result['address'];
    result['address'] = {
      meetingAdress: address,
      locateName: this.data.mapName,
      locateAddress: this.data.mapAddress,
      locateAtitude: this.data.mapLatitude,
      locateLongitude: this.data.mapLongitude
    }

    result["containNum"] = Number(result["containNum"]);

    

    if(result.timeList[0]){
      result.timeList[0] = {
        "specDate":currentDate,
        openTime:null
      }
    }
    if(result.timeList[1]){
      result.timeList[1] = {
        "specDate":tomorrow,
        openTime:null
      }
    }
    if(result.timeList[2]){
      result.timeList[2] = {
        "specDate":dayOfTomorrow,
        openTime:null
      }
    }

    console.log(result);


    wx.cloud.database().collection("meetingRoom").add({
      data: result,
      success: res => {
        if (res._id) {
          wx.showToast({
            title: '新增成功',
            duration: 1000
          })
          setTimeout(function () {
            wx.reLaunch({
              url: '/pages/index/index'
            })
          }, 1000)

          //给经纬度表单添加信息:编号，经度纬度，详细地址
          let mapMsg = {
            meetingId:res._id,
            longitude:this.data.mapLongitude,
            latitude:this.data.mapLatitude,
            detail:address,
            name:result.name
          }
          console.log(mapMsg);

          

          wx.cloud.database().collection("meetingMapMsg").add({
            data:mapMsg,
            success: res => {
              console.log(res)
            }
          })


        } else {
          wx.showToast({
            title: '服务器错误！',
            duration: 2000
          })
        }
      }
    })



  },

  //表单重置按钮
  formReset: function (e) {
    this.setData({
      allValue: ''
    })
  },

  //地区选择
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})